package com.dayuanit.dy15.atm.servlet;

import com.dayuanit.dy15.atm.domain.FlowDomain;
import com.dayuanit.dy15.atm.dto.FlowDTO;
import com.dayuanit.dy15.atm.dto.ResponseDTO;
import com.dayuanit.dy15.atm.entity.User;
import com.dayuanit.dy15.atm.exception.BizException;
import com.dayuanit.dy15.atm.holder.PageHolder;
import com.dayuanit.dy15.atm.service.FlowService;
import com.dayuanit.dy15.atm.service.impl.FlowServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class FlowServlet extends BaseServlet {

    private FlowService flowService = new FlowServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        System.out.println(">>>>>>>>flow request=" + req);
        String color = (String)req.getAttribute("color");
        System.out.println("******** color=" + color);

        try {
            if ("listFlows".equals(action)) {
                listFlows(req, resp);
            }

            if ("top10".equals(action)) {
                top10(req, resp);
            }
        } catch (BizException be) {
            //自定义异常，异常的信息可以给用户看
            be.printStackTrace();
            responseByAjax(ResponseDTO.fail(be.getMessage()), resp);
        } catch (Exception e) {
            //其他异常，都是未知异常，最好不要暴露给用户，用户都是邪恶的。
            e.printStackTrace();
            responseByAjax(ResponseDTO.fail("系统错误，请联系客服"), resp);
        }
    }

    private void listFlows(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String cardId = req.getParameter("cardId");
        String currentPage = req.getParameter("currentPage");

        PageHolder<List<FlowDTO>> pageHolder = flowService.queryFLows(Long.valueOf(cardId), Integer.parseInt(currentPage));

        //将结果序列化成JSON字符串
        responseByAjax(ResponseDTO.sucess(pageHolder), resp);
    }

    private void top10(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("loginUser");
        //将结果序列化成JSON字符串
        responseByAjax(ResponseDTO.sucess(flowService.top10(user.getId())), resp);
    }


}
